/**
 * Created by user on 2017/3/18.
 */

module.exports = function ($scope,$rootScope,$cookies, caseBarWritService,caseBarDetailFileService, pdfDelegate) {
  var vm = this;
  /*获取点击的案件的id*/
  var caseId = $cookies.get('caseAppId');

  vm.folders = [];//文件夹列表
  vm.selectedFolder = null;
  vm.getFolders = getFolders;
  vm.showFolder = showFolder;
  vm.createFolder = createFolder;
  //创建文件夹 接口
  vm.createFolderPort = createFolderPort;
  //删除文件夹  接口
  vm.deleteFolder = deleteFolder;
  //删除文件 接口
  // vm.deleteUpFile = deleteUpFile;
  vm.fileDelete = fileDelete;
  //文件夹重命名
  vm.fileRename = fileRename;
  //文件上重命名  接口
  vm.fileRenamePort = fileRenamePort;
  //文件下载 接口
  vm.fileDownload = fileDownload;
  //文件预览 接口
  vm.filePreview = filePreview;
  //文件预览关闭
  vm.filePreviewClose = filePreviewClose;
  //文件删除 接口
  // vm.deleteFile = deleteFile;
  //上传文件 接口
  vm.fileUpload = fileUpload;
  //上传文件
  // vm.upFiles = upFiles;

  vm.caseId = $cookies.get("caseAppId");
  //上传文件夹
  vm.uploadFiles = false;
  //自定义文件夹
  vm.customFolders = false;
  //自定义文件夹按钮
  vm.createFolderBtn = true;
  //文件列表的表头
  vm.tabTitle = false;
  //获取案件type类型
  $scope.type = $cookies.get('type');

  //自定义文件夹
  function createFolder() {
    vm.customFolders = !vm.customFolders;
    vm.customFolderName = '';
  }

  //初始化
  init();
  function init() {
    getFolders();

    $('.appendix-input').attr('disabled',false);

  }
  //获取文件夹列表
  function getFolders() {
    caseBarWritService.getFolders(vm.caseId).then(function (response) {
      if (response.data.code === 1) {
        vm.tabTitle = false;
        //获取成功
        vm.folders = response.data.data;
        if($rootScope.typeIf==7){

          $('.y-upload').bind('hover',function(){

            $(this).find('.showAction').css('display','none');
          })
        }
      }
    })
  }

  //点击显示文件列表
  function showFolder(folder) {
    $('.L_caseBarWritCont').css('display','block');
    vm.tabTitle = true;
    vm.createFolderBtn = false;
    if(folder == null) {
      vm.selectedFolder = null;
      vm.uploadFiles = false;
      vm.tabTitle = false;
      //自定义文件夹按钮
      vm.createFolderBtn = true;
    } else {
      vm.uploadFilesId = folder.folderId;
      vm.selectedFolder = folder;
      //刷新文件列表
      fileUpload();
      //文件夹的id
      vm.folderId = vm.selectedFolder.folderId;
      vm.tabTitle = false;
      $('.L_caseBarWritCont').css('display','none');
      if(vm.folderId<0){
        vm.uploadFiles = false;
      }else if(vm.folderId>=0){
        vm.uploadFiles = true;
      }
    }
  }

  //获取文件上传列表
  function fileUpload() {
    $rootScope.loadingShow = true;
    $rootScope.fadeShow = true;
    var params = {'caseId':vm.caseId};
    caseBarDetailFileService.fileUpload(params).then(function (data) {
      $rootScope.loadingShow = false;
      $rootScope.fadeShow = false;
      if (data.code == 1) {
      //刷新列表
      // vm.uploadFileList = data.data;
      // vm.selectedFolder.files.push(vm.uploadFileList);
      // // vm.selectedFolder.files.push(data.data);
      //selectedFolder
      // if(data.data.length==0){
      //   $('#file-empty-id').show();
      //   $('#file-container-id').hide();
      // }else{
      //   $('#file-empty-id').hide();
      //   $('#file-container-id').show();
      // }
      }
    }, function (response) {
      $rootScope.loadingShow = false;
      $rootScope.fadeShow = false;
      console.error('fileUpload error', response.status, response.statusText);
    });
  };

  $('.writ').change(function () {
    if(ckPhoto(this)){
      var fileData = new FormData();
      fileData.append('filename1',this.files[0]);
      fileData.append('caseId',vm.caseId);
      fileData.append('folderId',vm.uploadFilesId);
      $rootScope.loadingShow = true;
      $rootScope.fadeShow = true;
      caseBarWritService.filesUpload(fileData).then(function (response) {
        $rootScope.loadingShow = false;
        $rootScope.fadeShow = false;
        if(response.data.code==1){
          vm.uploadFileList = response.data.data;
          vm.selectedFolder.files.push(vm.uploadFileList);
        }
      });
    }else{

    }

  });
  function ckPhoto(obj) {
    var photoExt = obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase();
    var photoExtArr=['.mp3','.jpg,mp4','.pdf','.png','.docx','.pptx','.xlsx','.doc','.ppt','.xls'];
    if(photoExtArr.indexOf(photoExt)>-1) {

    }else{
      bootbox.dialog({
        message: "不支持该文件类型，目前支持文件类型为（mp3,jpg,mp4,pdf,png,docx,pptx,xlsx,doc,ppt,xls）",
        title: "提示信息",
        className:'d-promptBox',
        buttons: {
          OK: {
            label: "确定",
            className: "d-btn-confirm5",
            callback: function () {

            }
          }
        }
      });
      return false;
    }
    var fileSize = 0;
    fileSize = obj.files[0].size;
    fileSize = Math.round(fileSize / 1024 * 100) / 100;
    if(fileSize >= 10240*2) {
      bootbox.dialog({
        message: "上传文件大小不能超过20M，请重新选择上传",
        title: "提示信息",
        className:'d-promptBox',
        buttons: {
          OK: {
            label: "确定",
            className: "d-btn-confirm5",
            callback: function () {

            }
          }
        }
      });
      return false;
    }
    return true;
  }

  //创建文件夹
  function createFolderPort() {
    if(vm.customFolderName!=''&&vm.customFolderName!='文本不能为空'){
      var params = {"caseId":caseId,"folderName":vm.customFolderName};
      caseBarWritService.createFolderPort(params).then(function (response) {
        if(response.data.code == 1){
          //刷新文件夹列表
          getFolders();
          vm.customFolders = false;
        }
      })
    }else{
      vm.customFolderName='文本不能为空'
    }

  };
  //删除文件夹
  function deleteFolder(folder) {
    event.stopPropagation();
    var params = {'caseId':caseId,'folderId':folder.folderId};
    if(folder.files.length!=0){
      bootbox.dialog({
        message: "删除后会将文件夹中的文件一并删除，确认是否要删除",
        title: "提示信息",
        buttons: {
          Cancel: {
            label: "取消",
            // className: "btn-default",
            className: "btn-cancel",
            // confirmButtonColor: "#DD6B55",
            callback: function () {

            }
          },
          OK: {
            label: "确定",
            // className: "btn-default",
            className: "btn-confirm",
            // confirmButtonColor: "#DD6B55",
            callback: function () {
              caseBarWritService.deleteFolder(params).then(function (reponse) {
                if(reponse.data.code==1){
                  //刷新文件夹列表
                  getFolders();
                }

              })
            }
          }
        }
      });
    }else{
      bootbox.dialog({
        message: "确定删除此文件",
        title: "提示信息",
        buttons: {
          Cancel: {
            label: "取消",
            // className: "btn-default",
            className: "btn-cancel",
            // confirmButtonColor: "#DD6B55",
            callback: function () {

            }
          },
          OK: {
            label: "确定",
            // className: "btn-default",
            className: "btn-confirm",
            // confirmButtonColor: "#DD6B55",
            callback: function () {
              caseBarWritService.deleteFolder(params).then(function (reponse) {
                if(reponse.data.code==1){
                  //刷新文件夹列表
                  getFolders();
                }

              })
            }
          }
        }
      });
    }




  };

  //选择文件
  // $(".fileManager-upload").on("click", function () {
  //   document.getElementById("#upload-input").click();
  // });

  //选择文件
  /*$('#upload-input').on('change', function () {
    data = new FormData();
    data.append('filename1', this.files[0]);
    data.append("creatorId", userId);
    data.append("caseId", caseId);
    alert('上传',data);
    /!*是否为文本类型的正则表达式*!/
    var checkType = /^.*?\.(doc|DOC|xlsx|XLSX|txt|TXT|docx|DOCX|pdf|PDF|xls|XLS)$/;
    /!*如果选中的文件名不为空，则显示文件名*!/
    if (this.files[0].name != "" && this.files[0].name != null && this.files[0].name != undefined) {
      var fileName = this.files[0].name;
      var point = fileName.lastIndexOf(".");
      var fileType = fileName.substr(point);
      if(checkType.test(fileType)){
        $("#id-file-name").text(this.files[0].name);
      }else{
        $("#id-file-name").text("不支持所选文件类型，请重新选择");
      }
    }
  });*/
  //上传文件
  /*$("#submit-file").click(function (folder) {
      alert('11111');
      $rootScope.loadingShow = true;
      $rootScope.fadeShow = true;
      /!*caseId
       folderId*!/
      var data = {'caseId': caseId, 'folderId': folder.folderId};
      // if (data.get('filename1') != undefined && data.get('filename1') != null) {
      //   if (data.get('filename1').name == null || data.get('filename1').name == undefined
      //     || data.get('filename1').name == "") {
      //     $rootScope.loadingShow = false;
      //     $rootScope.fadeShow = false;
      //     alert("选择文件出错，请重新选择");
      //   } else {
      //     caseBarWritService.filesUpload(data).then(function (response) {
      //       $rootScope.loadingShow = false;
      //       $rootScope.fadeShow = false;
      //       if (response.code == 1) {
      //         $scope.fileUpload();
      //         $("#id-file-name").text("未选择任何文件");
      //
      //       }else{
      //         $rootScope.loadingShow = false;
      //         $rootScope.fadeShow = false;
      //         alert("抱歉！由于网络原因上传失败，请重试！");
      //       }
      //     }, function (response) {
      //       $rootScope.loadingShow = false;
      //       $rootScope.fadeShow = false;
      //       console.error('uploadPhoto error', response.status, response.statusText);
      //     });
      //   }
      // } else {
      //   alert("请选择一个文件");
      //   $rootScope.loadingShow = false;
      //   $rootScope.fadeShow = false;
      // }
      caseBarWritService.filesUpload(data).then(function (response) {
        $rootScope.loadingShow = false;
        $rootScope.fadeShow = false;
        fileUpload();
      })
    });*/

  /*//删除文件
  function deleteUpFile(file){
    var legalInstrumentTitle = $('#id-legalInstrumentTitle').text();
    $rootScope.loadingShow = true;
    $rootScope.fadeShow = true;
    /!*folderId
     folderFileId
     caseId*!/
    var params = {'folderId':file.folderId,'folderFileId':file.id,'caseId':caseId};
    if (file.fileName != undefined && file.fileName != "") {
      caseBarDetailFileService.delUpFile(params).then(function (data) {
        $rootScope.loadingShow = false;
        $rootScope.fadeShow = false;
        if (data.code == 1) {
          $scope.fileUpload();
        }
      }, function (response) {
        $rootScope.loadingShow = false;
        $rootScope.fadeShow = false;
        console.error('downUpFile error', response.status, response.statusText);
      });
    } else {
      alert("获取文件失败");
      $rootScope.loadingShow = false;
      $rootScope.fadeShow = false;
    }
  };*/

   //文件夹重命名
  function fileRename(folder) {
    folder.show = !folder.show;
  };
  //文件夹重命名 接口
  function fileRenamePort(folder) {
    var params = {'caseId':caseId,'folderId':folder.folderId,'folderName':folder.name};
    // $event.stopPropagation();
    caseBarWritService.fileRename(params).then(function (response) {
      if(response.data.code == 1){
        //刷新文件夹列表
        getFolders();
      }
    })
  };
  //文件下载
  function fileDownload(file) {
    var params = {'caseId':caseId,'folderId':vm.folderId,'folderFileId':file.id};
    caseBarWritService.fileDownload(params).then(function (response) {
      var files = new Blob([response.data]);
      var link = document.createElement('a');
      link.href = URL.createObjectURL(files);
      if(vm.folderId<0){
        link.download = file.fileName||file.name;
      }else {
        link.download = file.fileoriname;
      }

      link.click();
      window.URL.revokeObjectURL(link.href);
    });
  };
  //文件预览
  function filePreview(file) {
      var fileName = file.fileoriname || file.name || file.fileName;
      var suffix = "";
      if(fileName){
          var str= fileName.split(".");
          suffix = str[str.length-1];
          suffix = suffix.toLowerCase();
          var fileTypeList = [ 'jpg', 'pdf' , 'png' ];
          if(fileTypeList.indexOf(suffix) != -1){
              $('.Y-DD-InstrListG').attr('data-toggle','modal');
              $('.Y-DD-InstrListG').attr('data-target','#myModalPreview');

              var params = {'caseId':caseId,'folderId':vm.folderId,'folderFileId':file.id};

              caseBarWritService.filePreview(params).then(function (response) {
                  var files = new Blob([response.data]);
                  var link = URL.createObjectURL(files);
                // vm.filePreviewWindow = true;
                // vm.filePreViewHref = link;

                  if (suffix != 'pdf') {
                    $('#pdfViewerCanvas').hide();
                    $('.y-preview-img2').show();
                  } else {
                    $('#pdfViewerCanvas').show();
                    $('.y-preview-img2').hide();
                  }

                  if (suffix != 'pdf')
                    $rootScope.filePreViewHref = link;
                  else
                    pdfDelegate.$getByHandle('my-pdf-container').load(link);
              });
          }else {
              $('.Y-DD-InstrListG').attr('data-toggle',' ');
              $('.Y-DD-InstrListG').attr('data-target',' ');
              bootbox.dialog({
                  message: "此文件类型不支持预览",
                  title: "提示信息",
                  buttons: {
                      Cancel: {
                          label: "取消",
                          className: "btn-cancel",
                          callback: function () {

                          }
                      },
                      OK: {
                          label: "确定",
                          className: "btn-confirm",
                          callback: function () {

                          }
                      }
                  }
              });
          }
      }
  };
  //文件预览弹窗关闭
  vm.filePreviewWindow = false;
  function filePreviewClose() {
    vm.filePreviewWindow = false;
    window.URL.revokeObjectURL(vm.filePreViewHref);
  };
  //文件的删除
  function fileDelete(index,file) {
    var params = {'caseId':caseId,'folderId':vm.folderId,'folderFileId':file.id};
    bootbox.dialog({
      message: "确定删除文件",
      title: "提示信息",
      buttons: {
        Cancel: {
          label: "取消",
          // className: "btn-default",
          className: "btn-cancel",
          // confirmButtonColor: "#DD6B55",
          callback: function () {

          }
        },
        OK: {
          label: "确定",
          // className: "btn-primary",
          className: "btn-confirm",
          callback: function () {
            caseBarWritService.fileDelete(params).then(function (response) {
              if(response.data.code == 1){
                vm.selectedFolder.files.splice(index,1);
              }
            });
          }
        }
      }
    });

  }
};
